home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9605 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.0 KB  |  59 lines

  1. Path: news.acadia.net!usenet
  2. From: steven2@salesbook.com (Steve Nutt)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to copy an object?
  5. Date: Sun, 03 Mar 1996 06:21:24 GMT
  6. Organization: DET
  7. Message-ID: <4hb52h$8jd@post.acadia.net>
  8. References: <4h05rb$su6@atlas.tncnet.com>
  9. Reply-To: steven2@salesbook.com
  10. NNTP-Posting-Host: blf7.acadia.net
  11. X-Newsreader: Forte Free Agent 1.0.82
  12.  
  13. Simon Lee (Simon Lee) wrote:
  14.  
  15.  
  16. >Hello,
  17.  
  18. >I'm trying to have a member function return a duplicate copy of a
  19. >member data object.  How would I go about this?
  20.  
  21. >Ie.
  22.  
  23. >class x {
  24. >private:
  25. >    Y  *object_of_class_y;
  26.  
  27. >public:
  28. >    Y GetY();
  29. >};
  30.  
  31.  
  32. >I would like GetY() to return a copy of object_of_class_y, not a pointer
  33. >to it.
  34.  
  35. >Any email responses appreciated.
  36.  
  37. >-Simon
  38.  
  39.  
  40. You will need a copy constructor for class Y. You can then do either
  41.  
  42. class x {
  43. pribate:
  44.   Y* object_of_class_y;
  45.  
  46. public:
  47.   Y GetY () 
  48.     { 
  49.        CHECK (object_of_class_y);    // check that
  50. object_of_class_y != 0
  51.         return *object_of_class_y;
  52.     }
  53. };
  54.  
  55. or you could make GetY return a const Y&. This would be faster.
  56.  
  57. Steve
  58.  
  59.